from concurrent.futures.thread import ThreadPoolExecutor
from multiprocessing import Process

import json
import logging
import os
from requests_toolbelt.multipart.encoder import MultipartEncoder
import mimetypes

import time

import requests

appid = 'wx1042769b76361cb5'
secret = 'cb026be6635453bd7d24ba6917226764'
token_path = 'temp/access_token'

logging.basicConfig(level=logging.INFO)  # 设置日志级别

class IG:
    def __gettoken__(self):
        try:
            fp = open(token_path)
            data = fp.read()
            return data
        finally:
            if fp != None:
                fp.close()
        return

    def getTokenInTime(self):
        if os.path.exists(token_path):
            stat = os.stat(token_path)
            mtime = stat.st_mtime
            elapse_time = time.time() - mtime
            logging.info('elapse time:%d'%(elapse_time))
            if elapse_time < 7000:
                return self.__gettoken__()
        logging.info('renew token')
        res = requests.get(
            'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid, secret))
        data = res.json()


        if 'errcode' not in data:
            access_token = data['access_token']
            try:
                fp = open(token_path, 'w+')
                fp.write(access_token)
                return self.__gettoken__()
            finally:
                if fp != None:
                    fp.close()
    # commondity/20202020/szzs.py
    def uploadFile(self,uploadpath,filepath):
        print("upload file%s"%(uploadpath))
        accessToken=self.getTokenInTime()
        res=requests.post("https://api.weixin.qq.com/tcb/uploadfile?access_token=%s"%(accessToken),json={
            'env': 'blueboz-y2oq3',
            'path': uploadpath
        })
        data=res.json()
        print(data)
        if data['errcode']==0:
            url=data['url']
            authorization=data['authorization']
            file_id=data['file_id']
            token=data['token']
            cos_file_id=data['cos_file_id']

            #比较麻烦
            m = MultipartEncoder(
                fields={
                    'Signature': authorization,
                    'key': uploadpath,
                    "x-cos-security-token": token,
                    "x-cos-meta-fileid": cos_file_id,
                    'file': ('filename', open(filepath, 'rb'), mimetypes.guess_type(filepath))}
            )
            res = requests.post(url, headers={
                "Content-Type":m.content_type
            }, data=m)
            print(res.text)


    def uploadBinary(self,url):
        print("upload binary")


if __name__ == '__main__':
    basepath='/Volumes/Mac/Code/pycharm/MyAI/temp/20210110/commodity'
    coms=os.listdir(basepath)
    threadPool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test_")

    for com in coms:
        imgpath=os.path.join(basepath,com)
        if os.path.isdir(imgpath):
            files=os.listdir(imgpath)
            for file in files:
                print("up%s/%s"%(com,file))
                ig = IG()
                future = threadPool.submit(ig.uploadFile, 'commodity/%s/%s'%(com,file),os.path.join(imgpath,file))

    threadPool.shutdown(wait=True)
    print("finished")

    # print(mimetypes.guess_type('aa.jpg'))
    # pass

# requests.post("https://api.weixin.qq.com/tcb/uploadfile?access_token=ACCESS_TOKEN",)
# POST https://api.weixin.qq.com/tcb/uploadfile?access_token=ACCESS_TOKEN
